<template>
  <div class="update-photo">
    <img ref="img" class="img" :src="img">

    <div class="toolbar">
      <div class="cancel" @click="$emit('close')">取消</div>
      <div class="confirm" @click="onConfirm">完成</div>
    </div>
  </div>
</template>

<script>
import { updatephoto } from '@/api/user.js'
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
export default {
  props: {
    img: {
      type: [String, Object],
      required: true
    }
  },
  data() {
    return {

    }
  },

  created() {

  },
  mounted() {
    const image = document.querySelector('.img')
    this.cropper = new Cropper(image, {
      autoCropArea: 1, // 自动调整裁剪图片
      viewMode: 1, // 只能在裁剪的图片范围内移动
      cropBoxMovable: false, // 禁止裁剪区移动
      aspectRatio: 1,
      dragMode: 'move',
      cropBoxResizable: false, // 禁止裁剪区缩放
      background: false
    })
  },

  methods: {
    onConfirm() {
      this.$toast.loading({
        message: '保存中...',
        forbidClick: true, // 禁止背景点击
        duration: 0 // 持续展示
      })
      console.log(this.cropper.getCroppedCanvas())
      this.cropper.getCroppedCanvas().toBlob(async blob => {
        // console.log(blob)
        const formData = new FormData()
        formData.append('photo', blob)
        try {
          const res = await updatephoto(formData)
          console.log(res)
          this.$emit('updatephoto', res.photo)
          this.$toast.success('更新成功')
        } catch (err) {
          console.log(err)
          this.$toast.fail('更新失败')
        }
      })
    }
  }
}
</script>

<style scoped lang='less'>
.update-photo {
  background-color: #000;
  height: 100%;
  .toolbar {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: space-between;
    .cancel, .confirm {
      width: 90px;
      height: 90px;
      font-size: 30px;
      display: flex;
      justify-content: center;
      align-items: center;
      color: #fff;
    }
  }
}
.img {
  display: block;
  max-width: 100%;
}
</style>
